var express = require("express");
var router = express.Router();
var mongoose = require("mongoose");
var UserInfo = require("../models/userInfo");
var multer = require('multer');
var formidable = require('formidable');
var fs = require("fs");
//id 生成
var uuid = require('uuid/v1');
var uploadModel = require('./../util/uploadImage.js');//上传model

/*
 * 状态码 
 * 1001  用户名或密码错误       
 * 1002  用户名重复
 * 1003  亲！真不好意思，没有该用户名
 * 1004  新密码不能和老密码一样
 * 1005  只支持png和jpg格式图片
 * 1006  服务器忙！请重新上传
 */

//登录
router.post("/login", function(req, res, next) {
	var userName = req.body.userName;
	var userPassword = req.body.userPassword;

	UserInfo.find({
		userName: userName,
		userPassword: userPassword
	}, function(err, doc) {
		if(err) {
			res.json({
				status: 1,
				message: err.message,
				result: ""
			});
		} else {
			if(doc.length > 0) {
				res.cookie("userId", doc[0].userId, {
					path: "/",
					maxAge: 1000 * 60 * 60 * 24
				});
				res.cookie("userName", doc[0].userName, {
					path: "/",
					maxAge: 1000 * 60 * 60 * 24
				});
				res.json({
					status: 0,
					message: "",
					result: ""
				});
			} else {
				res.json({
					status: 1001,
					message: "error",
					result: "用户名或密码错误"
				});
			}
		}
	});
});

//获取用户信息
router.get("/getUserData", function(req, res, next) {
	var userId = req.query.userId;
	UserInfo.findOne({
		userId: userId
	}, function(err, doc) {
		if(err) {
			res.json({
				status: 1,
				message: err.message,
				result: ""
			});
		} else {
			res.json({
				status: 0,
				message: "",
				result: doc
			});
		}
	});
});

//用户注册
router.post("/registerUser", function(req, res, next) {
	var userName = req.body.userName;
	var userPassword = req.body.userPassword;
	var userPasswordVerify = req.body.userPasswordVerify;
	var userId = uuid(); //生成id

	UserInfo.find({}, function(err, doc) {
		if(err) {
			res.json({
				status: 1,
				message: err.message,
				result: ""
			});
		} else {
			if(doc) {
				var saveFlag = true;
				for(var i = 0; i < doc.length; i++) {
					if(userName == doc[i].userName) {
						saveFlag = false;
						break;
					}
				}
				if(saveFlag) {
					var userObj = {
						userId: userId,
						userName: userName,
						userPassword: userPassword,
						userHeadPortraitUrl: "",
						userDefaultHeadPortrait: "user_icon.png",
						orderList: [],
						cartList: [],
						addressList: []
					}
					var userInfo = new UserInfo(userObj);
					userInfo.save(function(err1, doc1) {
						if(err1) {
							res.json({
								status: 1,
								message: err1.message,
								result: ""
							});
						} else {
							res.json({
								status: 0,
								message: "",
								result: "恭喜您！账号注册成功"
							});
						}
					});
				} else {
					res.json({
						status: 1002,
						message: "",
						result: "用户名重复"
					});
				}
			}
		}
	});
});

//用户注销
router.post("/userLoginOut", function(req, res, next) {
	res.cookie("userId", "", {
		path: "/",
		maxAge: -1
	});
	res.cookie("userName", "", {
		path: "/",
		maxAge: -1
	});
	res.json({
		status: 0,
		message: "",
		result: ""
	});
});

//找回密码  验证用户名
router.post("/retrievePassVerifyUserName", function(req, res, next) {
	var userName = req.body.userName;

	var userTelphone = "";
	//随机生成 手机号码  
	var telHeaderArr = ["130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "153", "180", "181", "189", "177", "155", "156", "185", "186", "145", "176", "150", "151", "152", "157", "158", "159", "182", "183", "184", "187", "188", "147", "178"];
	for(var i = 0; i < 8; i++) {
		var telFooter = Math.floor(Math.random() * 9);
		userTelphone += telFooter;
	}
	userTelphoneStr = telHeaderArr[Math.floor(Math.random() * 33)] + userTelphone;

	UserInfo.find({
		userName: userName
	}, function(err, doc) {
		if(err) {
			res.json({
				status: 1,
				message: err.message,
				result: ""
			});
		} else {
			if(doc.length > 0) {
				res.json({
					status: 0,
					message: "",
					result: {
						message: "验证通过",
						userTelphone: userTelphoneStr,
						userName: doc[0].userName
					}
				});
			} else if(doc.length == 0) {
				res.json({
					status: 1003,
					message: "",
					result: "亲！真不好意思，没有该用户名"
				})
			}
		}
	});

});

//用户短信吗验证
router.get("/getTelCode", function(req, res, next) {
	var userTelphone = req.query.userTelphone;

	//生成随机六位验证码
	var telCode = "";
	for(var i = 0; i < 6; i++) {
		telCode += (Math.floor(Math.random() * 9)).toString();
	}

	res.json({
		status: 0,
		message: "",
		result: {
			telCode: telCode
		}
	});
});

//短信验证码比对
router.post("/verifyTelCode", function(req, res, next) {
	//用户输入的验证码
	var codeTel = req.body.codeTel;
	//用户获取的短信验证码
	var telCodeData = req.body.telCodeData;

	if(codeTel == telCodeData) {
		res.json({
			status: 0,
			message: "",
			result: {
				message: "验证通过"
			}
		});
	} else {
		res.json({
			status: 1,
			message: "",
			result: {
				message: "输入验证码不正确"
			}
		});
	}
});

//修改密码
router.post("/updatePassword", function(req, res, next) {
	var userName = req.body.userName;
	var newPassword = req.body.newPassword;
	var verifyNewPassword = req.body.verifyNewPassword;
	console.log(newPassword);

	UserInfo.find({
		"userName": userName
	}, function(err, doc) {
		if(err) {
			res.json({
				status: 1,
				message: err.message,
				result: ""
			});
		} else {
			if(doc) {
				var updateFlag = true;
				if(newPassword == doc[0].userPassword) {
					updateFlag = false;
					res.json({
						status: 1004,
						message: "新密码不能和老密码一样",
						result: {
							message: "新密码不能和老密码一样"
						}
					});
				}

				if(updateFlag) {
					UserInfo.update({
						"userName": userName
					}, {
						"userPassword": newPassword
					}, function(err1, doc1) {
						if(err1) {
							res.json({
								status: 1,
								message: err1.message,
								result: ""
							});
						} else {
							res.json({
								status: 0,
								message: "",
								result: {
									message: "密码修改成功"
								}
							});
						}
					});
				}
			}
		}
	});
});

//上传图片
router.post("/addPicture", function(req, res, next) {
	var userId = req.cookies.userId;
	var form = new formidable.IncomingForm();   //创建上传表单
	    form.encoding = 'utf-8';		//设置编辑
	  	form.uploadDir = 'public/uploadImage/';	 //设置上传目录
	  	form.keepExtensions = true;	 //保留后缀
	  	form.maxFieldsSize = 2 * 1024 * 1024;   //文件大小
	form.parse(req, function(err, fields, files) {
		if (err) {
			res.json({
				status : 1,
				message : err,
				result : {}
			})
		  return;		
		}  
	   
		var extName = '';  //后缀名
		switch (files.file.type) {
			case 'image/pjpeg':
				extName = 'jpg';
				break;
			case 'image/jpeg':
				extName = 'jpg';
				break;		 
			case 'image/png':
				extName = 'png';
				break;
			case 'image/x-png':
				extName = 'png';
				break;		 
		}

		if(extName.length == 0){
			res.json({
				status : 1005,
				message : '只支持png和jpg格式图片',
				result : {},
			})
			return;				   
		}

		var avatarName = uuid() + '.' + extName;
		var newPath = "C:/Users/zhangpan/Desktop/myWeb/panpan_project/static/"+ form.uploadDir + avatarName;
		fs.renameSync(files.file.path, newPath);//重命名
		
		UserInfo.findOne({userId : userId}, function (err, doc) {
			if (err) {
				res.json({
					status : 1,
					message : err,
					result : ""
				})
			}else {
				if (doc) {
					UserInfo.update({userId : userId},{"userHeadPortraitUrl" : avatarName}, function (err1, doc1) {
						if (err1) {
							res.json({
								status : 1006,
								message : "服务器忙！请重新上传",
								result : ""
							})
						}else {
							if (doc1) {
								res.json({
									status : 0,
									message : '上传成功',
									result : {},
								})
							}
						}
					})
				}
			}
		});
	});	
});

module.exports = router;